import java.util.concurrent.*;

public class Thread2 {
    public static void main(String[] args)
    {
        // 用ThreadPoolExecutor类初始化线程池
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());

        RunnableTask runnableTask1 = new RunnableTask("Jerry");
        RunnableTask runnableTask2 = new RunnableTask("Cissie");

        // execute方法执行Runnable类型的任务
        threadPoolExecutor.execute(runnableTask1);
        threadPoolExecutor.execute(runnableTask2);

        // 关闭线程池
        threadPoolExecutor.shutdown();


        // 用Executors类的工场方法初始化线程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);

        // 初始化Callable类型的任务
        MyCallableTask myCallableTask1 = new MyCallableTask(1);
        MyCallableTask myCallableTask2 = new MyCallableTask(1);

        Future<Integer> future1 = fixedThreadPool.submit(myCallableTask1);
        Future<Integer> future2 = fixedThreadPool.submit(myCallableTask2);

        // 关闭线程池
        fixedThreadPool.shutdown();

        // 主线程获取异步任务的执行结果
        System.out.println("主线程获取异步任务的执行结果");
        try{
            System.out.println("Future1的结果: " + future1.get());
            System.out.println("Future2的结果: " + future2.get());
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }
    }

    static class RunnableTask implements Runnable
    {
        String val;

        public RunnableTask(String val)
        {
            this.val = val;
        }

        @Override public void run()
        {
            System.out.println(Thread.currentThread().getName() + "执行Runnable任务，打印值：" + this.val);
        }
    }

    static class MyCallableTask implements Callable<Integer>
    {
        int sum;

        public MyCallableTask(int sum)
        {
            this.sum = sum;
        }

        @Override public Integer call() throws Exception
        {
            System.out.println(Thread.currentThread().getName() + "执行Callable任务");
            for (int i = 0; i < 100; ++i)
            {
                sum += i;
            }
            return sum;
        }
    }
}
